package cn.touna.jss.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA-256加密工具类
 * Created by wuwc on 2018/1/30.
 */
public class ShaUtil {

    private static final Logger logger = LogManager.getLogger(ShaUtil.class);

    /**
     * 加密
     *
     * @param strText 待加密文本
     * @param strType 加密类型
     * @return
     */
    public static String encrypt(final String strText, final String strType) throws NoSuchAlgorithmException {

        String strResult = null;

        if (StringUtils.isNotBlank(strText)) {
            // SHA 加密开始
            MessageDigest messageDigest = MessageDigest.getInstance(strType);
            // 传入要加密的字符串
            messageDigest.update(strText.getBytes());
            // 得到 byte 類型结果
            byte byteBuffer[] = messageDigest.digest();
            StringBuffer strHexString = new StringBuffer();
            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            strResult = strHexString.toString();
        }
        return strResult;
    }
}
